﻿@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section styles{
<style>
    .uploader-list .handle {
        background-color: #eee;
        color: red;
        filter: alpha(Opacity=80);
        -moz-opacity: 0.5;
        opacity: 0.5;
        width: 240px;
        text-align: right;
    }

        .uploader-list .handle i {
            margin-right: 5px;
        }

        .uploader-list .handle i:hover {
            cursor: pointer;
        }

        .uploader-list {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            width: 1000px;
            flex-wrap: wrap;
        }

        .uploader-list .file-iteme {
            display: flex;
            padding: 5px;
            flex-direction: column;
        }

    .trdel {
        cursor: pointer;
    }
</style>
}
<script src="/js/xm-select.js" type="text/javascript"></script>
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" lay-filter="content-form" style="padding: 15px 0 0 0;">
            <input type="hidden" value="@Model.Id" name="Id" />
            <input type="hidden" value="@Model.ChannelId" name="ChannelId" />
            <div class="layui-row layui-col-space10">
                <div class="layui-col-md10">
                    @if (ViewBag.FieldList != null)
                    {
                        foreach (var item in ViewBag.FieldList)
                        {
                            switch (item.InputType)
                            {
                                case "Text":
                                    await Html.RenderPartialAsync("_InputText", item as TablestyleInput);
                                    break;
                                case "Number":
                                    await Html.RenderPartialAsync("_InputNumber", item as TablestyleInput);
                                    break;
                                case "TextArea":
                                    await Html.RenderPartialAsync("_InputTextArea", item as TablestyleInput);
                                    break;
                                case "TextEditor":
                                    await Html.RenderPartialAsync("_InputTextEditor", item as TablestyleInput);
                                    break;
                                case "CheckBox":
                                    await Html.RenderPartialAsync("_InputCheckBox", item as TablestyleInput);
                                    break;
                                case "Radio":
                                    await Html.RenderPartialAsync("_InputRadio", item as TablestyleInput);
                                    break;
                                case "SelectOne":
                                    await Html.RenderPartialAsync("_InputSelectOne", item as TablestyleInput);
                                    break;
                                case "SelectMultiple":
                                    await Html.RenderPartialAsync("_InputSelectMultiple", item as TablestyleInput);
                                    break;
                                case "Date":
                                    await Html.RenderPartialAsync("_InputDate", item as TablestyleInput);
                                    break;
                                case "DateTime":
                                    await Html.RenderPartialAsync("_InputDateTime", item as TablestyleInput);
                                    break;
                                case "Image":
                                    await Html.RenderPartialAsync("_InputImage", item as TablestyleInput);
                                    break;
                                case "Video":
                                    await Html.RenderPartialAsync("_InputVideo", item as TablestyleInput);
                                    break;
                                case "File":
                                    await Html.RenderPartialAsync("_InputFile", item as TablestyleInput);
                                    break;
                                default:
                                    await Html.RenderPartialAsync("_InputText", item as TablestyleInput);
                                    break;
                            }
                        }
                    }
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="content-submit" id="content-submit">确定</button>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md2">
                    <div class="layui-tab" lay-filter="content-setting">
                        <ul class="layui-tab-title">
                            <li class="layui-this">设置</li>
                        </ul>
                        <div class="layui-tab-content">
                            <div class="layui-tab-item layui-show">
                                <div class="layui-collapse" lay-accordion="">

                                    <div class="layui-colla-item">
                                        <h2 class="layui-colla-title">审核状态</h2>
                                        <div class="layui-colla-content ">
                                            <div style="margin:10px;">
                                                <select name="Checked">
                                                    <option value="1" @(1==Model.Checked?"selected":"")>草稿</option>
                                                    <option value="2" @(2==Model.Checked?"selected":"")>待审核</option>
                                                    <option value="3" @(3==Model.Checked?"selected":"")>已审核</option>
                                                    <option value="4" @(4==Model.Checked?"selected":"")>终审退稿</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="layui-colla-item">
                                        <h2 class="layui-colla-title">内容属性</h2>
                                        <div class="layui-colla-content ">
                                            <div style="margin:10px;">
                                                <input type="checkbox" name="Top" lay-skin="primary" title="置顶" @(1==Model.Top?"checked":"")>
                                                <input type="checkbox" name="Recommend" lay-skin="primary" title="推荐" @(1==Model.Recommend?"checked":"")>
                                                <input type="checkbox" name="Hot" lay-skin="primary" title="热点" @(1==Model.Hot?"checked":"")>
                                                <input type="checkbox" name="Color" lay-skin="primary" title="醒目" @(1==Model.Color?"checked":"")>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="layui-colla-item">
                                        <h2 class="layui-colla-title">内容组</h2>
                                        <div class="layui-colla-content">
                                            <div style="margin:10px;">
                                                @if (ViewBag.GroupNamesList != null)
                                                {
                                                    foreach (var item in ViewBag.GroupNamesList)
                                                    {
                                                        <input type="checkbox" name="c_gname" lay-skin="primary" value="@item["GroupName"]" title="@item["GroupName"]" @(item["Checked"] =="1"?"checked":"")>
                                                    }
                                                }
                                            </div>
                                        </div>
                                    </div>

                                    <div class="layui-colla-item">
                                        <h2 class="layui-colla-title">标签</h2>
                                        <div class="layui-colla-content ">
                                            <div style="margin:10px;">
                                                @if (ViewBag.TagNamesList != null)
                                                {
                                                    foreach (var item in ViewBag.TagNamesList)
                                                    {
                                                        <input type="checkbox" name="c_tag" lay-skin="primary" value="@item["TagName"]" title="@item["TagName"]" @(item["Checked"] =="1"?"checked":"")>
                                                    }
                                                }
                                            </div>
                                        </div>
                                    </div>

                                    <div class="layui-colla-item">
                                        <h2 class="layui-colla-title">内容链接</h2>
                                        <div class="layui-colla-content ">
                                            <div style="margin:10px;">
                                                <p>链接类型</p>
                                                <div style="margin:5px ;">
                                                    <select name="LinkType" lay-filter="linktype">
                                                        <option value="None" @("None"==Model.LinkType?"selected":"")>默认</option>
                                                        <option value="NoLink" @("NoLink"==Model.LinkType?"selected":"")>不可链接</option>
                                                        <option value="LinkToChannel" @("LinkToChannel"==Model.LinkType?"selected":"")>链接到指定栏目</option>
                                                    </select>
                                                </div>
                                                <div class="channelUrl" style="display:@(Model.LinkType=="LinkToChannel"?"":"none");">
                                                    <p>链接栏目</p>
                                                    <div style="margin:5px ;">
                                                        <input id="channelcascader" name="ChannelUrl" />
                                                    </div>
                                                </div>
                                                <div class="linkurl" style="display:@(Model.LinkType=="None"?"":"none");">
                                                    <p>外部链接</p>
                                                    <div style="margin:5px ;">
                                                        <textarea name="LinkUrl" id="LinkUrl" placeholder="设置后栏目链接将转向此链接" class="layui-textarea"></textarea>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="layui-colla-item">
                                        <h2 class="layui-colla-title">添加时间</h2>
                                        <div class="layui-colla-content">
                                            <div style="margin:10px;">
                                                <input type="text" name="AddTime" id="addtime" autocomplete="off" class="layui-input">
                                            </div>

                                        </div>
                                    </div>

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>

    </div>
</div>
@section scripts{

<script type="text/javascript">
      var content_controls = {
      textEditor:@Html.Raw(ViewBag.TextEditor),
      textVideo:@Html.Raw(ViewBag.TextVideo),
      textImage:@Html.Raw(ViewBag.TextImage),
      textFile:@Html.Raw(ViewBag.TextFile),
      textData:@Html.Raw(ViewBag.TextData),
      textDataTime:@Html.Raw(ViewBag.TextDataTime),
      textCheckbox:@Html.Raw(ViewBag.TextCheckbox),
      textMultiple:@Html.Raw(ViewBag.TextMultiple)
    };
    var  content_values= new Array();

    var  content_extend_items ={
     extendValues: @Html.Raw(Model.ExtendValues),
     extendRules:@Html.Raw(ViewBag.RuleList)
    };


</script>
<script type="text/javascript">

        layui.use(['lscom', 'form', 'upload', 'tinymce', 'layCascader', 'element', 'laydate', 'preview'], function () {
        var $ = layui.$;
        var lscom = layui.lscom;
        var form = layui.form;
        var edit_body;
        var tinymce = layui.tinymce;
        var upload = layui.upload;
        var layCascader = layui.layCascader;
        var element =layui.element;
        var index = parent.layer.getFrameIndex(window.name);
        var laydate  =layui.laydate;
        let preview = layui.preview;
        //parent.layer.iframeAuto(index);

        laydate.render({
            elem: '#addtime'
            ,type: 'datetime'
            ,value: new Date()
        });

        lscom.ajax({
            url: "/Cms/Channel/GetChannleCascader?channelId=0",
            type:'GET',
            lsHandleError: false
        }).done(function(data) {
            if (data.code == 0) {
                layCascader({
                    elem: '#channelcascader',
                    options: data.data,
                    value: ('@Model.LinkType'=='LinkToChannel' ? '@Model.LinkUrl':''),
                    clearable: true
                });
            }
        }).fail(function(message) {
            lscom.notify.error(message);
        });

         preview.render({
                model: "img",
                domName: '.zoomImg'
            });


       init();
       eventclick();

       form.on('select(linktype)', function(data) {
            var slval = data.value;
            if(slval=="None"){
                 $('.linkurl').show();
                 $('.channelUrl').hide();
            }else if(slval=="LinkToChannel"){
                 $('.linkurl').hide();
                 $('.channelUrl').show();
            }else{
                $('.linkurl').hide();
                 $('.channelUrl').hide();
            }
        });

        form.on('submit(content-submit)', function (data) {

          for(var editor in content_controls.textEditor){
               var key =content_controls.textEditor[editor];
               data.field[key] =content_values[key].getContent();
            }

          for(var video in content_controls.textVideo){
                var key =content_controls.textVideo[video];

                var videoids = [];
                $('#upload_file_list_'+key+'input[type="hidden"]').each(function () {
                    videoids.push($(this).val());
                });
               data.field[key] = videoids.join(',');
            }
            for(var image in content_controls.textImage){
                var key =content_controls.textImage[image];
                var imageids = [];
                $('#uploader_list_'+key+' .file-iteme').each(function () {
                 imageids.push($(this).prop("id"));
                });
                data.field[key] = imageids.join(',');
            }
            for(var f in content_controls.textFile){
                var key =content_controls.textFile[f];

                var fileids = [];
               $('#upload_file_list_'+key+'input[type="hidden"]').each(function () {
                    fileids.push($(this).val());
                });
               data.field[key] = fileids.join(',');
            }
            for(var chk in content_controls.textCheckbox){
                var key =content_controls.textCheckbox[chk];
                var chkids = [];
               $('input[name="'+key+'"]:checked').each(function () {
                    chkids.push($(this).val());
                });
               data.field[key] = chkids.join(',');
            }
            //console.log(data.field);

            if(data.field.LinkType=="LinkToChannel"){
                data.field.LinkUrl = data.field.ChannelUrl;
            }
            data.field.Top = data.field.Top=="on"?1:0;
            data.field.Recommend = data.field.Recommend=="on"?1:0;
            data.field.Hot = data.field.Hot=="on"?1:0;
            data.field.Color = data.field.Color=="on"?1:0;

            var c_gnames=[];
            $('input[name="c_gname"]:checked').each(function(){
            c_gnames.push($(this).val());
            });
            data.field.GroupNameCollection= c_gnames.join(',');
             var c_tags=[];
            $('input[name="c_tag"]:checked').each(function(){
            c_tags.push($(this).val());
            });
            data.field.Tags= c_tags.join(',');


            var field = data.field;

            var waitIndex = parent.layer.load(2);
            lscom.ajax({
                url: "/Cms/Content/SaveData",
                data: JSON.stringify(field),
                lsHandleError: false
            }).done(function (data) {
                if (data.code == 0) {
                    lscom.notify.success(data.message);
                    setTimeout(function(){
                            var  muilttab = localStorage.getItem("muilt-tab");
                            if (muilttab=="true") {
                            parent.layui.admin.refresh(10011);
                            parent.layer.close(waitIndex);
                            parent.layui.admin.closeCurrentTab();
                        }
                        parent.layui.admin.jump(10011,"内容管理",'/Cms/Content/Index');
                    },1000); 
                }
            }).fail(function (message) {
                lscom.notify.error(message);
            }).always(function () {
                parent.layer.close(waitIndex);
            });
            return false;
        });

        function  eventclick(){
            $(document.body).on('click','.trdel',function(){
              $(this).parents('tr').remove();
            });

            $(document.body).on('click','.delimag',function(){
              $(this).parents('.file-iteme').remove();
            });
        }

        function  init(){
            for(var editor in content_controls.textEditor){
                var key =content_controls.textEditor[editor];
                content_values[key] =texteditor('Content_'+key);
            }
            for(var video in content_controls.textVideo){
                 var key =content_controls.textVideo[video];
                 videoupload(key);
                 if(key=="VideoUrlIds"){
                     filedataload(key,'@Model.VideoUrlIds');
                 }
                 else{

                 }
            }
            for(var image in content_controls.textImage){
                 var key =content_controls.textImage[image];
                 imgupload(key);
                 if(key=="ImageUrlIds"){
                      imagdataload(key,'@Model.ImageUrlIds');
                 }
                 else{

                 }
            }
            for(var file in content_controls.textFile){
                var key =content_controls.textFile[file];
                fileupload(key);
                if(key=="FileUrlIds"){
                      filedataload(key,'@Model.FileUrlIds');
                 }
                 else{

                 }
            }
            for(var td in content_controls.textData){
              var key =content_controls.textData[td];
                laydate.render({
                elem: '#data_'+key
                });
            }
            for(var tdt in content_controls.textDataTime){
              var key =content_controls.textDataTime[tdt];
                laydate.render({
                elem: '#data_'+key,
                type:"datetime"
                });
            }
        }

        function texteditor(controlId){
           return  tinymce.render({
                elem: "#"+controlId,
                menubar: false ,
                plugins: 'print preview searchreplace autolink fullscreen image link media code codesample table charmap hr pagebreak nonbreaking anchor advlist lists textpattern help emoticons autosave indent2em axupimgs kityformula-editor' ,
                //toolbar: 'code undo redo restoredraft | cut copy | forecolor backcolor bold italic underline strikethrough link | alignleft aligncenter alignright alignjustify | bullist numlist blockquote subscript superscript removeformat | \
                //    formatselect fontselect fontsizeselect | \
                //    table image media charmap emoticons hr pagebreak print preview | fullscreen | indent2em lineheight axupimgs kityformula-editor' ,
                    toolbar: ['code undo redo restoredraft | cut copy | forecolor backcolor bold italic underline strikethrough link | alignleft aligncenter alignright alignjustify | bullist numlist blockquote subscript superscript removeformat ',
                        ' formatselect fontselect fontsizeselect |table image media charmap emoticons hr pagebreak print preview  | indent2em lineheight axupimgs kityformula-editor'],
                autosave_ask_before_unload: false ,
                font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats;' ,

                images_upload_url: '/Upload/UploadTinymceFile?category=content',
                images_upload_base_path: '/',
                paste_data_images: false,
                file_picker_types: 'file media',
                height: 350,
                //自定义文件选择器的回调内容 此方法只有在点击上方图片按钮才会触发
                file_picker_callback: function (callback, value, meta) {
                     if (meta.filetype === 'media') {
                        // 动态创建上传input，并进行模拟点击上传操作，达到本地上传视频效果。
                        let input = document.createElement('input');
                        //创建一个隐藏的
                        input.setAttribute('type', 'file');
                        input.setAttribute("accept", ".mp4");
                        //let that = this;
                        input.onchange = function () {
                            let file = this.files[0];
                            let formData = new FormData();
                            formData.append("file", file);
                            formData.append("category", "content");
                            var waitIndex = parent.layer.load(2);
                            lscom.ajax({
                                url: "/Upload/UploadFile",
                                data: formData,
                                lsHandleError: false,
                                processData: false,
                                contentType: false,
                            }).done(function (data) {
                                if (data.code == 0) {
                                    callback(data.data.url);
                                }
                            }).fail(function (message) {
                                parent.layer.msg(message, { icon: 5 });
                            }).always(function () {
                               parent.layer.close(waitIndex);
                            });
                        }
                        //触发点击
                        input.click();
                    }
                     if (meta.filetype === 'file') {
                          // 动态创建上传input，并进行模拟点击上传操作，达到本地上传视频效果。
                        let input = document.createElement('input');
                        //创建一个隐藏的
                        input.setAttribute('type', 'file');
                        input.setAttribute("accept", ".pdf");
                        //let that = this;
                        input.onchange = function () {
                            let file = this.files[0];
                            let formData = new FormData();
                            formData.append("file", file);
                            formData.append("category", "content");
                            var waitIndex = parent.layer.load(2);
                            lscom.ajax({
                                url: "/Upload/UploadFile",
                                data: formData,
                                lsHandleError: false,
                                processData: false,
                                contentType: false,
                            }).done(function (data) {
                                if (data.code == 0) {
                                    callback(data.data.url);
                                }
                            }).fail(function (message) {
                                parent.layer.msg(message, { icon: 5 });
                            }).always(function () {
                               parent.layer.close(waitIndex);
                            });
                        }
                        //触发点击
                        input.click();
                     }
                },
                images_upload_handler: function (blobInfo, succFun, failFun) {
                    var xhr, formData;
                    var file = blobInfo.blob();//转化为易于理解的file对象

                    formData = new FormData();
                    formData.append('file', file, file.name);
                    formData.append("category", "channel");

                    var waitIndex = parent.layer.load(2);
                    lscom.ajax({
                        url: "/Upload/UploadFile",
                        data: formData,
                        lsHandleError: false,
                        processData: false,
                        contentType: false,
                    }).done(function (data) {
                        if (data.code == 0) {
                            if (data.data != null && data.data.url != "") {
                                succFun(data.data.url);
                            }
                        }
                    }).fail(function (message) {
                        parent.layer.msg(message, { icon: 5 });
                    }).always(function () {
                        parent.layer.close(waitIndex);
                    });
                }
           });
       }

        
       function  imgupload(controlId){
            upload.render({
            elem: '#mul_'+controlId
            , url: '/Upload/UploadFile?category=content' //此处配置你自己的上传接口即可
            , multiple: false
            , size: 4096
            , accept: 'images'
            , acceptMime: 'image/jpg,image/jpeg,image/png'
            , before: function (obj) {

            }
            , done: function (res) {
                //上传完毕
                $('#uploader_list_'+controlId).append(
                    '<div id="' + res.data.id + '" class="file-iteme">' +
                    '<div class="handle"><i class="layui-icon layui-icon-delete delimag"></i></div>' +
                    '<img class="zoomImg" style="width: 240px; height: 180px; border: none;" src=' + res.data.url + '>' +
                    '<div class="info"></div>' +
                    '</div>'
                );
            }
            });
       }

       function  imagdataload(controlId,ids){
            if(ids==null || ids=="") return false;
            lscom.ajax({
            url: "/Systems/Files/CustomerFileList?ids="+ids,
            type:'GET',
            lsHandleError: false
            }).done(function(data) {
                if (data.code == 0) {
                    var _tr ='';
                    $.each(data.data,function(k,v){
                       _tr += '<div id="' + v.id + '" class="file-iteme">';
                       _tr += '<div class="handle"><i class="layui-icon layui-icon-delete delimag"></i></div>' ;
                            _tr += '<img class="zoomImg" style="width: 240px; height: 180px; border: none;" src=' + v.fpath + '>';
                       _tr +=  '<div class="info"></div>' ;
                       _tr +=  '</div>';
                    })
                     $('#uploader_list_'+controlId).append(_tr);
                }
            }).fail(function(message) {
                lscom.notify.error(message);
            });
        }

        function  videoupload(controlId) {
            upload.render({
                elem: '#mulv_'+controlId
                , url: '/Upload/UploadFile?category=content' //此处配置你自己的上传接口即可
                , multiple: false
                , accept: 'file'
                , exts: 'mp4'
                , before: function(obj) {

                }
                , done: function(res) {
                    //上传完毕
                    var htmltr = '<tr>';
                    htmltr += '<td> <input type="hidden" value="' + res.data.id + '" /><a href="' + res.data.url + '"  target="_blank">' + res.data.filename + '</a></td>';
                    htmltr += '<td><span class="layui-badge trdel">删除</span></td>';
                    htmltr += '</tr>';

                    $('#upload_file_list_'+controlId+' tbody').append(htmltr);
                }
            });
        }

        function  filedataload(controlId,ids){
            if(ids==null || ids=="") return false;
            lscom.ajax({
            url: "/Systems/Files/CustomerFileList?ids="+ids,
            type:'GET',
            lsHandleError: false
            }).done(function(data) {
                if (data.code == 0) {
                    var _tr ='';
                    $.each(data.data,function(k,v){
                       var htmltr = '<tr>';
                        htmltr += '<td> <input type="hidden" value="' + v.id + '" /><a href="' + v.fpath + '"  target="_blank">' + v.fname + '</a></td>';
                        htmltr += '<td><span class="layui-badge trdel">删除</span></td>';
                        htmltr += '</tr>';
                        _tr += htmltr;
                    })
                    $('#upload_file_list_'+controlId+' tbody').append(_tr);
                }
            }).fail(function(message) {
                lscom.notify.error(message);
            });
        }

        function  fileupload(controlId){
             upload.render({
                elem: '#mulf_'+controlId
                , url: '/Upload/UploadFile?category=content' //此处配置你自己的上传接口即可
                , multiple: false
                , accept: 'file'
                , exts: 'pdf|xlsx|docx'
                , before: function(obj) {

                }
                , done: function(res) {
                    //上传完毕
                    var htmltr = '<tr>';
                    htmltr += '<td> <input type="hidden" value="' + res.data.id + '" /><a href="' + res.data.url + '"  target="_blank">' + res.data.filename + '</a></td>';
                    htmltr += '<td><span class="layui-badge trdel">删除</span></td>';
                    htmltr += '</tr>';

                    $('#upload_file_list_'+controlId+' tbody').append(htmltr);
                }
            });
        }

    });

</script>
}

